class PeipeiduiController < ApplicationController

  layout 'xiaonei'
  acts_as_xiaonei_controller

  RANDOM_FRIENDS_SEED = 100

  def index
    @user = xiaonei_session.invoke_method("xiaonei.users.getInfo", :uids => params[:xn_sig_user], :fields => Xiaonei::User.attr_names.join(","))     
    @user = @user.first
    
    @friends = xiaonei_session.invoke_method("xiaonei.friends.getFriends")    
   
    # 是否是从 couple_link 过来的链接
    # 如果是则下面不用再执行
    @my_rate_couple = Couple.find(:first, 
                                  :conditions => [" id = ? ", params[:my_rate_couple_id]]) if params[:my_rate_couple_id]
    if @my_rate_couple
      @left_friend = Xiaonei::User.new
      @left_friend.uid = @my_rate_couple.first_user_id.to_s
      @right_friend = Xiaonei::User.new
      @right_friend.uid = @my_rate_couple.second_user_id.to_s
      return
    end

    if params[:gender]
      # TODO 判断朋友过少，导致某些情况下不成对的bug
     case params[:gender]
     when "gb" :
       @left_friend = get_friend_by_sex  @friends, "0"
       @right_friend = get_friend_by_sex  @friends, "1"
     when "gg" :
       @left_friend = get_friend_by_sex  @friends, "0"
       @right_friend = get_friend_by_sex  @friends.delete(@left_friend), "0"       
     when "bb" :
       @left_friend = get_friend_by_sex  @friends, "1"
       @right_friend = get_friend_by_sex  @friends.delete(@left_friend), "1"           
     end 
    else
      # 默认是 girls & boys
      @left_friend = get_friend_by_sex  @friends, "0"
      @right_friend = get_friend_by_sex  @friends, "1"
    end

    @pre_couple = Couple.find(:first, :conditions => [" id = ? ", params[:couple_id]]) if params[:couple_id]

  end

  def rating
    # 做一些rating的计算
    @couple = Couple.find(:first, :conditions => ["(first_user_id = ? and second_user_id = ? ) or (first_user_id = ? and second_user_id = ? ) ", params[:left_friend], params[:right_friend], params[:left_friend], params[:right_friend]]) || Couple.new({:first_user_id => params[:left_friend], :second_user_id => params[:right_friend]})
    @couple.save! if @couple.new_record?

    # 使用 Xiaonei::User 作为 rater
    @rate_user = Xiaonei::User.new
    @rate_user.uid = params[:xn_sig_user]

    @couple.rate params[:rating].to_i, @rate_user
    make_xiaonei_redirection ({:controller => :peipeidui, 
                              :action => :index, 
                              :couple_id => "#{ @couple.id.to_s }", 
                              :gender => "#{params[:gender]}", 
                              :last_rating => params[:rating] })

    #ret = xiaonei_session.invoke_method("xiaonei.feed.publishTemplatizedAction", 
    #                                    :template_id => "1", 
    #                                    :uid => params[:xn_sig_user], 
    #                                    :resource_id => params[:xn_sig_user])
    #logger.debug("--------- #{ret.inspect}")     
  end

  # 热度榜
  def couples
    check_app_user

    @hottest_couples = Couple.paginate(:all, 
                                    :order => "rating_avg DESC",
                                    :conditions => "rating_count > 1",
                                    :page => params[:page], 
                                    :per_page => 8)
    @votest_couples = Couple.paginate(:all, 
                                    :order => "rating_count DESC",
                                    :page => params[:page], 
                                    :per_page => 8)
    @newest_couples = Couple.paginate(:all, 
                                    :order => "updated_at DESC",
                                    :conditions => "rating_avg > 0",
                                    :page => params[:page], 
                                    :per_page => 8)
  end


  # 获取couple的详细信息
  def couple_link
    check_app_user
    @couple = Couple.find(:first, :conditions => [" id = ? ", params[:couple_link]]) if params[:couple_link]
    make_xiaonei_redirection ({:controller => :peipeidui, :action => :couples })  unless @couple  
  end

  # 获取rater的详细信息
  def rater
    check_app_user
    @couple = Couple.find(:first, :conditions => [" id = ? ", params[:couple_link]]) if params[:couple_link]
    make_xiaonei_redirection ({:controller => :peipeidui, :action => :couples })  unless @couple
    @raters = Rating.find(:all, :conditions => [" rated_id = ? and rated_type = 'Couple' ", @couple.id.to_s ])
  end

  # 个人信息
  def people
    check_app_user
    if params[:people_id]
      @people = Xiaonei::User.new
      @people.uid = params[:people_id]
    end

    make_xiaonei_redirection ({:controller => :xiaonei, :action => :index })  unless @people

    @couple = Couple.find(:first, 
                          :conditions => ["(first_user_id = ? and second_user_id = ? ) or (first_user_id = ? and second_user_id = ? ) ", params[:xn_sig_user], params[:people_id], params[:people_id], params[:xn_sig_user]])
    @couple = Couple.create({:first_user_id => params[:xn_sig_user], :second_user_id => params[:people_id]}) unless @couple
  end  

  protected

  def get_friend_by_sex(all_friends=nil, sex="0")
    all_friends = xiaonei_session.invoke_method("xiaonei.friends.getFriends") unless all_friends
    # 从中查找一个好友
    if all_friends.size <= RANDOM_FRIENDS_SEED
      users_ids = all_friends.collect { |f| f.id }
      select_user_by_sex_from_uids(users_ids, sex)
    else
      # 为了节省带宽，每次只随机选择RANDOM_FRIENDS_SEED个连续好友
      # 如果这RANDOM_FRIENDS_SEED个好友里面都没有一个符合要求的好友，那就有点变态了
      rnd = rand(all_friends.size)
      users_ids = ( (rnd + RANDOM_FRIENDS_SEED) > all_friends.size ? all_friends[rnd..(rnd+RANDOM_FRIENDS_SEED)] + all_friends[0..(rnd+RANDOM_FRIENDS_SEED-all_friends.size)] : all_friends[rnd..(rnd+RANDOM_FRIENDS_SEED)] ).collect { |f| f.id }
      select_user_by_sex_from_uids(users_ids, sex) 
    end
  end

  def select_user_by_sex_from_uids(uids=[], sex="0")
    users = xiaonei_session.invoke_method("xiaonei.users.getInfo", 
                                                  :uids => uids.join(","), 
                                                  :fields => ("sex"))      
    users = users.select { |f| f.sex == sex}
    if users    
      users[rand(users.size)] 
    else
      nil
    end
  end
 
end
